package com.liannong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liannong.entity.UserCart;
import com.liannong.entity.Product;
import com.liannong.exception.BusinessException;
import com.liannong.mapper.UserCartMapper;
import com.liannong.mapper.ProductMapper;
import com.liannong.service.UserCartService;
import com.liannong.service.WarehouseService;
import com.liannong.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserCartServiceImpl extends ServiceImpl<UserCartMapper, UserCart> implements UserCartService {

    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private WarehouseService warehouseService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addToCart(Integer userId, Integer productId, Integer quantity) {
        // 检查商品是否存在
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 检查购物车是否已存在该商品
        QueryWrapper<UserCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("product_id", productId);
        UserCart existingCart = this.getOne(queryWrapper);
        
        if (existingCart != null) {
            // 更新数量
            existingCart.setQuantity(existingCart.getQuantity() + quantity);
            existingCart.setUpdateTime(LocalDateTime.now());
            return this.updateById(existingCart);
        } else {
            // 新增购物车项
            UserCart userCart = new UserCart();
            userCart.setUserId(userId);
            userCart.setProductId(productId);
            userCart.setQuantity(quantity);
            userCart.setPrice(product.getPrice());
            userCart.setSelected(true); // 默认选中状态
            userCart.setCreateTime(LocalDateTime.now());
            userCart.setUpdateTime(LocalDateTime.now());
            return this.save(userCart);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateQuantity(Long cartId, Integer quantity) {
        UserCart userCart = this.getById(cartId);
        if (userCart == null) {
            throw new BusinessException("购物车项不存在");
        }
        
        userCart.setQuantity(quantity);
        userCart.setUpdateTime(LocalDateTime.now());
        return this.updateById(userCart);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSelected(Long cartId, Boolean selected) {
        UserCart userCart = this.getById(cartId);
        if (userCart == null) {
            throw new BusinessException("购物车项不存在");
        }
        
        userCart.setSelected(selected);
        userCart.setUpdateTime(LocalDateTime.now());
        return this.updateById(userCart);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeFromCart(Long cartId) {
        return this.removeById(cartId);
    }

    @Override
    public List<CartVO> getUserCart(Integer userId) {
        QueryWrapper<UserCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<UserCart> cartItems = this.list(queryWrapper);
        
        return cartItems.stream()
                .map(this::convertToCartVO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean clearCart(Integer userId) {
        QueryWrapper<UserCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.remove(queryWrapper);
    }
    
    private CartVO convertToCartVO(UserCart userCart) {
        CartVO cartVO = new CartVO();
        cartVO.setCartId(userCart.getCartId());
        cartVO.setUserId(userCart.getUserId());
        cartVO.setProductId(userCart.getProductId());
        cartVO.setQuantity(userCart.getQuantity());
        cartVO.setPrice(userCart.getPrice());
        cartVO.setSelected(userCart.getSelected());
        cartVO.setCreateTime(userCart.getCreateTime());
        cartVO.setUpdateTime(userCart.getUpdateTime());
        
        // 获取商品名称
        Product product = productMapper.selectById(userCart.getProductId());
        if (product != null) {
            cartVO.setProductName(product.getName());
        }
        
        return cartVO;
    }
} 